import { ErrorHandler, FeedbackManager } from '../../utils/errorHandler.js'

Page({
  data: {
    logs: [],
    loading: false,
    selectedLevel: 'all', // all, error, warning, info
    filteredLogs: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.loadErrorLogs()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadErrorLogs()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 加载错误日志
   */
  loadErrorLogs() {
    this.setData({ loading: true })
    
    try {
      const logs = ErrorHandler.getErrorLogs()
      const processedLogs = logs.map(log => ({
        ...log,
        formattedTime: this.formatTime(log.timestamp),
        levelColor: this.getLevelColor(log.level)
      })).reverse() // 最新的在前面
      
      this.setData({
        logs: processedLogs,
        loading: false
      })
      
      this.filterLogs()
    } catch (error) {
      console.error('加载错误日志失败:', error)
      this.setData({ loading: false })
      FeedbackManager.showError('加载错误日志失败')
    }
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date
    
    if (diff < 60000) { // 1分钟内
      return '刚刚'
    } else if (diff < 3600000) { // 1小时内
      return Math.floor(diff / 60000) + '分钟前'
    } else if (diff < 86400000) { // 1天内
      return Math.floor(diff / 3600000) + '小时前'
    } else {
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
    }
  },

  /**
   * 获取错误级别颜色
   */
  getLevelColor(level) {
    const colors = {
      info: '#3cc51f',
      warning: '#ffa502',
      error: '#ff4757',
      fatal: '#c44569'
    }
    return colors[level] || '#666'
  },

  /**
   * 切换错误级别筛选
   */
  onLevelChange(e) {
    const level = e.currentTarget.dataset.level
    this.setData({ selectedLevel: level })
    this.filterLogs()
  },

  /**
   * 筛选日志
   */
  filterLogs() {
    const { logs, selectedLevel } = this.data
    let filteredLogs = logs
    
    if (selectedLevel !== 'all') {
      filteredLogs = logs.filter(log => log.level === selectedLevel)
    }
    
    this.setData({ filteredLogs })
  },

  /**
   * 查看日志详情
   */
  viewLogDetail(e) {
    const index = e.currentTarget.dataset.index
    const log = this.data.filteredLogs[index]
    
    const detail = `时间: ${log.formattedTime}
级别: ${log.level.toUpperCase()}
类型: ${log.type}
错误: ${log.error}
上下文: ${JSON.stringify(log.context, null, 2)}
设备信息: ${JSON.stringify(log.userAgent, null, 2)}
${log.stack ? '堆栈: ' + log.stack : ''}`
    
    wx.showModal({
      title: '错误详情',
      content: detail,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 清除所有日志
   */
  clearAllLogs() {
    FeedbackManager.showConfirm({
      title: '清除日志',
      content: '确定要清除所有错误日志吗？',
      confirmText: '清除',
      confirmColor: '#ff4757',
      onConfirm: () => {
        const success = ErrorHandler.clearErrorLogs()
        if (success) {
          FeedbackManager.showSuccess('日志清除成功')
          this.setData({
            logs: [],
            filteredLogs: []
          })
        } else {
          FeedbackManager.showError('日志清除失败')
        }
      }
    })
  },

  /**
   * 导出日志
   */
  exportLogs() {
    try {
      const logs = this.data.logs
      if (logs.length === 0) {
        FeedbackManager.showWarning('暂无日志可导出')
        return
      }
      
      const exportData = {
        title: 'TodoList 错误日志',
        exportTime: new Date().toISOString(),
        totalCount: logs.length,
        logs: logs
      }
      
      // 这里可以实现实际的导出功能
      // 比如保存到文件或发送到服务器
      wx.showModal({
        title: '导出日志',
        content: `准备导出 ${logs.length} 条错误日志`,
        showCancel: true,
        confirmText: '确定导出',
        success: (res) => {
          if (res.confirm) {
            FeedbackManager.showSuccess('日志导出成功')
          }
        }
      })
    } catch (error) {
      console.error('导出日志失败:', error)
      FeedbackManager.showError('导出日志失败')
    }
  },

  /**
   * 分享日志统计
   */
  shareLogStats() {
    const logs = this.data.logs
    const stats = {
      total: logs.length,
      error: logs.filter(log => log.level === 'error').length,
      warning: logs.filter(log => log.level === 'warning').length,
      info: logs.filter(log => log.level === 'info').length,
      fatal: logs.filter(log => log.level === 'fatal').length
    }
    
    const shareText = `TodoList 错误日志统计：
📊 总计：${stats.total} 条
❌ 错误：${stats.error} 条
⚠️ 警告：${stats.warning} 条
ℹ️ 信息：${stats.info} 条
💀 致命：${stats.fatal} 条

应用运行状态监控中...`
    
    wx.showModal({
      title: '日志统计',
      content: shareText,
      showCancel: false,
      confirmText: '知道了'
    })
  }
}) 